# coding=utf-8
"""
    日志记录
"""

import os
import logging
from logging.handlers import TimedRotatingFileHandler

# @Time    :  2024-10-17 11:16:07
# @Author  :  jiangtong
# @Email   :  gingerqgyy@outlook.com
# @Project :  ginger_yl_test_boost
# @File    :  log_util

import os
import logging
import threading
from logging.handlers import TimedRotatingFileHandler
from utils.path_util import LOG_PATH


# 日志封装 : ( 为了兼容 Flask 的 logger, 这里将所有日志设置放在 app.logger 上 )
class LoggerUtil:
    _logger = None
    _lock = threading.Lock()

    LOG_FILE = os.path.join(LOG_PATH, 'app.log')

    def __new__(cls, app):
        with cls._lock:
            if not cls._logger:
                if app is None:
                    raise ValueError('App instance must be provided to initialize the logger.')

                # 获取并配置 Flask 的 app.logger, 不自行定义 : _logger = logging.getLogger('ginger-yl-test-boost')
                _logger = app.logger
                log_level = logging.getLevelName(app.config.get('LOG_LEVEL', 'INFO'))
                _logger.setLevel(log_level)

                # 输出到控制台
                console_handler = logging.StreamHandler()
                console_handler.setLevel(log_level)
                log_format = '%(asctime)s %(levelname)s %(thread)s %(message)s [in %(pathname)s:%(lineno)d]'
                console_handler.setFormatter(logging.Formatter(log_format))
                _logger.addHandler(console_handler)

                # 创建日志文件目录
                os.makedirs(LOG_PATH, exist_ok=True)

                # 输出到文件，按天切割日志
                file_handler = TimedRotatingFileHandler(cls.LOG_FILE, when='midnight', interval=1, backupCount=7, encoding='utf-8')
                file_handler.suffix = "%Y-%m-%d.log"
                file_handler.setFormatter(logging.Formatter(log_format))
                file_handler.setLevel(log_level)
                _logger.addHandler(file_handler)
            cls._logger = _logger
        return cls._logger
